package com.njbw.design_pattern.created.singleton;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 长沙先飞信息科技有限公司<br>
 * Created with IntelliJ IDEA.<br>
 * Date:2025/8/27<br>
 * Time:19:56<br>
 * 功能描述：<br>
 * 全局计数器,基于单例模式实现——饿汉式
 *
 * @author huang hou chun
 * @since JDK 1.8 <br>
 * Copyright (c) 2023 www.csxfrj.com System Incorporated All Rights Reserved.
 */
public class GlobalCounter {

    private final AtomicLong atomicLong = new AtomicLong(0);
    // 静态私有实例,类加载时创建,使用静态的特性来保证全局唯一性！！！
    // 因为类加载时天然是线程安全的，所以这种方式也是线程安全的，而 static 是类级别的，所以这种方式也保证了全局唯一性
    private static final GlobalCounter INSTANCE = new GlobalCounter();

    // 私有化无参构造器 防止外部通过 new 来创建对象
    private GlobalCounter() {}

    public static GlobalCounter getInstance() {
        return INSTANCE;
    }

    public long getId() {
        return atomicLong.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                for (int j = 0; j < 1000; j++) {
                    // 查看当前的统计数量
                    long currentNumber = GlobalCounter.getInstance().getId();
                    System.out.println(Thread.currentThread().getName() + " : " + currentNumber);
                }
            });
        }
        TimeUnit.SECONDS.sleep(10);
        executorService.shutdown();
    }
}
